package com.yonyou.cyxdms.sysAuth.service.controller;


import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cyx.framework.controller.base.BaseController;
import com.yonyou.cyx.framework.service.http.HttpRequestService;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyx.function.utils.security.Md5Util;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.dto.*;
import com.yonyou.cyxdms.sysAuth.service.dto.user.LoginDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserInfoDto;
import com.yonyou.cyxdms.sysAuth.service.feign.IAuthProviderService;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserLoginMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.dealerchannel.MsgTemplateService;
import com.yonyou.cyxdms.sysAuth.service.vo.user.BindingPhoneVO;
import com.yonyou.cyxdms.sysAuth.service.vo.weChat.SmsWxVo;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.ExtraDTO;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.PushMsgDTO;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.SmsPushDTO;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserRoleDTO;
import com.yonyou.cyxdms.sysmanage.client.service.login.EmployeeClientService;
import com.yonyou.cyxdms.sysmanage.client.service.login.LoginService;
import com.yonyou.cyxdms.sysmanage.client.service.login.PushServices;
import com.yonyou.cyxdms.sysmanage.client.vo.role.UserbyRoleVO;
import io.swagger.annotations.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 此Controller 主要实现登录、退出、修改密码等功能
 *
 * @author adu
 *         * @date 2019-08-19
 */
@Api(value = "登录", tags = {"登录"})
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController {


    @Value("${app.name}")
    private String appName;
    // 定义日志接口getMenus
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    public UserLoginService userLoginService;

    @Autowired
    private IAuthProviderService authProviderService;

    @Autowired
    private SystemParamService systemParamService;

    @Autowired
    UserService userService;

    @Autowired
    public RedissonClient redissonClient;

    @Autowired
    HttpRequestService httpService;

    @Autowired
    public MsgTemplateService msgTemplateService;

    @Autowired
    public UserLoginMapper userLoginMapper;

    @Autowired
    public UserMapper userMapper;

    /**
     * 执行登录操作
     *
     * @param userLoginDto
     * @return
     * @throws Exception
     * @author adugetMenus
     * @date 2019-08-19
     */
    @RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "登录操作")
    public Map<String, Object> login(@ApiParam(name = "登录操作", value = "登录操作", required = true) @RequestBody UserLoginDTO userLoginDto,
                                     @ApiParam(name = "User-Agent", value = "User-Agent", required = true) @RequestHeader(value = "User-Agent") String userAgent,
                                     @ApiParam(name = "userAgent", value = "userAgent") @RequestHeader(value = "userAgent", defaultValue = "pc") String userLogWay) throws Exception {
        Integer logWay;
        if (userLogWay.equals("pc")) {
            logWay = 10041001;
        } else {
            logWay = 10041002;
        }
        if (!StringUtils.isNullOrEmpty(userLoginDto.getRegId())) {
            String messageFormat = StrUtil.format("cyxdms.sysManager.login.regId.lock.{}",
                    userLoginDto.getRegId(), userLoginDto.getRegId());
            RLock lock = redissonClient.getLock(messageFormat);
            try {
                boolean res = lock.tryLock(0, 300, TimeUnit.SECONDS);
                if (!res) {
                    throw new ServiceBizException("接口正在被调用,发生并发");
                }
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
        Map<String, Object> dataMap = userLoginService.login(userLoginDto, userAgent, logWay);
        return dataMap;
    }


    /**
     * 刷新验证码
     *
     * @param username
     * @param deviceId
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author renwd
     * @since 2019/3/7
     */
    @ApiOperation(value = "刷新验证码")
    @GetMapping("/refreshVerification")
    public Map<String, Object> refreshVerification(@RequestParam(required = false, defaultValue = "cyx") String appId,
                                                   @RequestParam("username") String username,
                                                   @RequestParam(value = "deviceId", required = false) String deviceId) throws IOException {
        return userLoginService.refreshVerification(appId, username, deviceId);
    }

    /**
     * 获取用户相关
     *
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "获取用户相关")
    public Map<String, Object> getappUserData() {
        return userLoginService.appUserData();
    }

    /**
     * 获取用户相关
     *
     * @return
     * @author maxingjian
     * @date 2019-09-21
     */
    @RequestMapping(value = "/detailNew", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", name = "userId", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(value = "appId", name = "appId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "获取用户相关")
    public Map<String, Object> getappUserDataNew() {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> returnMap = new HashMap<>();
        if (UserAuthConstant.APP_SOURCE_BEIJING.equals(loginInfoDto.getAppId())) {
            returnMap = userLoginService.appBjUserDataNew();
        } else {
            returnMap = userLoginService.appUserDataNew();
        }
        return returnMap;
    }

    /**
     * 售后平板获取角色类别
     *
     * @return
     * @author maxingjian
     * @date 2019-11-15
     */
    @RequestMapping(value = "/detailForPad", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "Pad获取用户相关")
    public List<UserRoleDTO> getDetailForPad() {
        return userLoginService.getDetailForPad();
    }

    /**
     * PC登录后获取角色进行选择
     *
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/roleDetail", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "获取用户相关角色")
    public List<UserRoleDTO> roleDetail() {
        return userLoginService.roleDetail();
    }


    /**
     * App应用通过jwt校验用户是否已经登录
     *
     * @return 如何登录了返回用户账号，否则返回空
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/appAuthCas", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户Id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "jwt校验用户是否已经登录")
    public String appAuthCas() {
        return userLoginService.appAuthCas();
    }


    /**
     * 退出
     *
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户Id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    public String logout(@ApiParam(name = "jwt", value = "jwt", required = true) @RequestParam String jwt, @RequestHeader(value = "userLoginId", required = false) Long userLoginId) {
        return userLoginService.logout(jwt, userLoginId);
    }

    /**
     * 退出
     *
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/reflesh", method = RequestMethod.GET)
    @ApiOperation(value = "更新信息")
    public String reflesh(@ApiParam(name = "jwt", value = "jwt", required = true) @RequestParam String jwt) {
        String nonce = "1";
        String occurtime = String.valueOf(System.currentTimeMillis());
        String sign = Sign(nonce, occurtime);
        Map login = new HashMap();
        login = userLoginService.getLoginUser();
        authProviderService.updateJwtInfo(jwt, nonce, occurtime, sign, login);
        return "";
    }

    /**
     * 检查
     *
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    @RequestMapping(value = "/checkRole", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工ID", name = "employeeId", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(value = "ROLE", name = "appRole", required = false, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "检查role")
    public String checkRole() {
        return userLoginService.checkRole();
    }

    private String Sign(String nonce, String occurtime) {
        String authorizationCode = "3a863974aa4bef6ba71c";
        String data = authorizationCode + nonce + occurtime;
        return Md5Util.md5(data).toLowerCase();
    }

    /**
     * TODO 获取登录用户相关
     *
     * @param userId
     * @return
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getLoginInfoNew2")
    @ApiOperation(value = "获取登录用户相关")
    public LoginInfoDto getLoginInfo(@ApiParam(name = "userId", value = "登录操作", required = true) @RequestParam(value = "userId") String userId
            , @ApiParam(name = "userAgent", value = "设备", required = true) @RequestParam(value = "userAgent") String userAgent
            , @ApiParam(name = "flag", value = "flag", required = true) @RequestParam(value = "flag") boolean flag
    ) throws Exception {
        LoginInfoDto dto = userLoginService.getLoginInfoDto(userId, userAgent, flag);
        String role = userLoginService.getRole(userId);
        if (!StringUtils.isNullOrEmpty(role)) {
            dto.setAppRole(Long.parseLong(role));
            logger.debug("============----------重新获取role----------===========");
        }
        return dto;
    }

    /**
     * TODO 获取登录用户相关
     *
     * @param userId
     * @return
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getLoginInfoNew")
    @ApiOperation(value = "获取登录用户相关")
    public LoginInfoDto getLoginInfo(@ApiParam(name = "userId", value = "登录操作", required = true) @RequestParam(value = "userId") String userId
            , @ApiParam(name = "userAgent", value = "设备", required = true) @RequestParam(value = "userAgent") String userAgent
    ) throws Exception {
        LoginInfoDto dto = userLoginService.getLoginInfoDto(userId, userAgent, false);
        String role = userLoginService.getRole(userId);
        if (!StringUtils.isNullOrEmpty(role)) {
            dto.setAppRole(Long.parseLong(role));
            logger.debug("============----------重新获取role----------===========");
        }
        return dto;
    }

    /**
     * TODO 保存角色
     *
     * @param appRole
     * @return
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/setRole")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "保存角色")
    public String setRole(@ApiParam(name = "appRole", value = "角色", required = true) @RequestParam String appRole) throws Exception {
        return userLoginService.setRole(appRole);
    }

    /**
     * TODO 选择角色
     *
     * @param userRoleDTO
     * @return
     * @throws Exception
     * @author maxingjian
     * @date 2019-09-16
     */
    @RequestMapping(method = RequestMethod.POST, value = "/setUserRole")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "保存角色")
    public String setUserRole(@ApiParam(name = "选择角色", value = "选择角色", required = true) @RequestBody UserRoleDTO userRoleDTO) throws Exception {
        return userLoginService.setUserRole(userRoleDTO);
    }

    /**
     * u
     * TODO 保存角色swargger专用
     *
     * @param appRole
     * @return
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/setRoleWithId", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保存角色swargger专用")
    public String setRole(@ApiParam(name = "appRole", value = "角色", required = true) @RequestParam String appRole,
                          @ApiParam(name = "userId", value = "用户id", required = true) @RequestParam String userId) {
        return userLoginService.setRole(appRole, userId);
    }

    /**
     * TODO 获取角色
     *
     * @return String
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getRole")
    @ApiOperation(value = "获取角色")
    public String getRole(@ApiParam(name = "userId", value = "用户id", required = true) @RequestParam String userId) throws Exception {
        return userLoginService.getRole(userId);
    }


    /**
     * TODO 获取角色
     *
     * @return String
     * @throws Exception
     * @author maxingjian
     * @date 2019-02-27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getRoles", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取所有角色")
    public Map<String, Object> getRoles(@ApiParam(name = "userId", value = "员工编号", required = false) @RequestParam String userId) throws Exception {
        return userLoginService.getRoles(userId);
    }

    /**
     * @description：根据员工编号获取登录账号
     * @author ：quankk
     * @date ：Created in 2019/2/28 14:48
     * @modified By：
     */
    @RequestMapping(value = "/emp", method = RequestMethod.GET)
    @ApiOperation(value = "根据员工编号获取登录账号")
    public EmployeeDTO emp(@ApiParam(name = "appId", value = "appId", required = true) @RequestParam("appId") String appId,
                           @ApiParam(name = "employeeNo", value = "员工编号", required = true) @RequestParam("employeeNo") String employeeNo) {
        return userLoginService.emp(appId, employeeNo);
    }

    /**
     * @description：修改密码
     * @author ：quankk
     * @date ：Created in 2019/3/4 14:53
     * @modified By：
     */
    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST, produces = "application/json")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", required = true, dataType = "string", paramType = "header", value = "登录账号主键ID")})
    public String updatePassword(@Valid @RequestBody PasswordDTO passwordDTO) throws Exception {
        return userLoginService.updatePassword(passwordDTO);
    }

    /**
     * @description：查询当前版本号
     * @author ：quankk
     * @date ：Created in 2019/3/5 16:52
     * @modified By：
     */
    @ApiOperation(value = "查询当前版本号")
    @RequestMapping(value = "/appVersionNo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Map<String, String> appVersionNo(@ApiParam(name = "appType", value = "app类型", required = true) @RequestParam("appType") String appType,
                                            @ApiParam(name = "appId", value = "appId", required = false) @RequestParam(required = false, defaultValue = "cyx") String appId) {
        return userLoginService.appVersionNo(appType, appId);
    }

    /**
     * @description：根据条件查询用户
     * @author ：quankk
     * @date ：Created in 2019/3/7 15:35
     * @modified By：
     */
    @ApiOperation(value = "根据条件查询用户")
    @RequestMapping(value = "/userByCondition", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public List<UserDTO> userByCondition(@RequestBody UserDTO userDTO) {
        return userLoginService.userByCondition(userDTO);
    }

    /**
     * @description：更新版本号
     * @author ：quankk
     * @date ：Created in 2019/3/12 14:18
     * @modified By：
     */
    @ApiOperation(value = "更新版本号")
    @RequestMapping(value = "/updateAppVersion", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String updateAppVersion(@ApiParam(name = "appType", value = "app类型", required = true) @RequestParam("appType") String appType,
                                   @ApiParam(name = "appVersion", value = "app版本号", required = true) @RequestParam("appVersion") String appVersion,
                                   @ApiParam(name = "appId", value = "appId", required = true) @RequestParam("appId") String appId) {
        return userLoginService.updateAppVersion(appType, appVersion, appId);
    }

    /**
     * @description：消息推送
     * @author ：quankk
     * @date ：Created in 2019/3/21 16:32
     * @modified By：
     */
    @RequestMapping(value = "/pushByUserIdOrEmpNo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消息推送")
    public String pushByUserIdOrEmpNo(@Valid @RequestBody PushDTO pushDTO) {
        return userLoginService.pushByUserIdOrEmpNo(pushDTO);
    }

    /**
     * @description：消息推送，推送的人不需要关注极光还是IM
     * @author ：maxingjian
     * @date ：Created in 2019/12/24
     * @modified
     */
    @RequestMapping(value = "/pushMsg", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @ApiOperation(value = "消息推送")
    void pushMsg(@RequestBody PushMsgDTO pushMsgDTO) {
        userLoginService.pushMsg(pushMsgDTO);
    }


    @RequestMapping(value = "/pushBy", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消息推送")
    public void pushBy(@RequestParam(value = "userIds", required = true) Integer userIds,
                       @RequestParam(value = "title", required = false, defaultValue = "") String title,
                       @RequestParam(value = "templateCode", required = true, defaultValue = "") Integer templateCode,
                       @RequestBody Map<String, Object> templateContentMap
    ) {
        String appId = userMapper.selectById(userIds).getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new DALException("AppId不存在!");
        }
        ExtraDTO extraDTO = new ExtraDTO();
        extraDTO.setTemplateCode(templateCode);
        String templateName = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateName();
        extraDTO.setTzType(templateName);
        extraDTO.setPushType(SysAuthCommonConstants.NOTICE_TZ);
        long t1 = System.currentTimeMillis();
        extraDTO.setDateTime(t1);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        PushDTO pushDTO = new PushDTO();
        pushDTO.setUserId(userIds);
        if (!StringUtils.isNullOrEmpty(appId)) {
            loginInfoDto.setAppId(appId);
        }
        pushDTO.setTitle(title);
        if (templateCode == null) {
            throw new RuntimeException("模板code参数有误！");
        }
        String templateDesc = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateDesc();
        for (Map.Entry<String, ?> content : templateContentMap.entrySet()) {
            String key = content.getKey();
            String val = content.getValue().toString();
            if (templateDesc.indexOf(key) > -1) {
                key = "\\{" + key + "\\}";
                templateDesc = templateDesc.replaceAll(key, val);
            }
        }
        pushDTO.setContent(templateDesc);
        pushDTO.setMode("notify");
        if (StringUtils.isNullOrEmpty(pushDTO.getTitle())) {
            String appNameQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.APP_NAME, loginInfoDto.getAppId());
            pushDTO.setTitle((StringUtils.isNullOrEmpty(appNameQ) ? appName : appNameQ));
        }
        if (StringUtils.isNullOrEmpty(pushDTO.getContent())) {
            pushDTO.setContent("模板错误！");
        }
        pushDTO.setExtra(extraDTO);
        pushByUserIdOrEmpNo(pushDTO);
    }

    /**
     * @Description:t推送消息，参数从body中获取
     * @Param:
     * @return:
     * @Author: wangsht
     * @Date: 2021/5/13
     */
    @RequestMapping(value = "/pushInfoBy", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消息推送")
    public void pushInfoBy(@RequestBody String data) {
        Map<String, Object> map = JSONUtil.jsonToMap(data);
        Integer userIds = Integer.valueOf(map.get("userIds").toString());
        String title = map.get("title").toString();
        String content = map.get("content").toString();

        Integer templateCode = Integer.valueOf(map.get("templateCode").toString());
        Map<String, Object> templateContentMap = (Map<String, Object>) map.get("templateContentMap");
        String appId = userMapper.selectById(userIds).getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new DALException("AppId不存在!");
        }
        ExtraDTO extraDTO = new ExtraDTO();
        extraDTO.setTemplateCode(templateCode);
        String templateName = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateName();
        extraDTO.setTzType(templateName);
        extraDTO.setPushType(SysAuthCommonConstants.NOTICE_TZ);
        long t1 = System.currentTimeMillis();
        extraDTO.setDateTime(t1);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        PushDTO pushDTO = new PushDTO();
        pushDTO.setUserId(userIds);
        if (!StringUtils.isNullOrEmpty(appId)) {
            loginInfoDto.setAppId(appId);
        }
        pushDTO.setTitle(title);
        if (templateCode == null) {
            throw new RuntimeException("模板code参数有误！");
        }
        pushDTO.setContent(content);
        pushDTO.setMode("notify");
        if (StringUtils.isNullOrEmpty(pushDTO.getTitle())) {
            String appNameQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.APP_NAME, loginInfoDto.getAppId());
            pushDTO.setTitle((StringUtils.isNullOrEmpty(appNameQ) ? appName : appNameQ));
        }
        if (StringUtils.isNullOrEmpty(pushDTO.getContent())) {
            pushDTO.setContent("模板错误！");
        }
        pushDTO.setExtra(extraDTO);
        pushByUserIdOrEmpNo(pushDTO);
    }

    /**
     * @Description: 智慧通激光推送
     * @Param:
     * @return:
     * @Author: wangsht
     * @Date: 2021/3/10
     */
    @RequestMapping(value = "/pushByZhi", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消息推送")
    public void pushByZhi(
            @RequestBody Map<String, Object> paramMap
    ) {
        Integer userIds = Integer.parseInt(paramMap.get("userIds").toString());
        Integer templateCode = Integer.parseInt(paramMap.get("templateCode").toString());
        String title = paramMap.get("title").toString();
        Map<String, String> templateContentMap = (Map<String, String>) paramMap.get("templateContentMap");
        String appId = userMapper.selectById(userIds).getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new DALException("AppId不存在!");
        }
        ExtraDTO extraDTO = new ExtraDTO();
        extraDTO.setTemplateCode(templateCode);
        String templateName = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateName();
        extraDTO.setTzType(templateName);
        extraDTO.setPushType(SysAuthCommonConstants.NOTICE_TZ);
        long t1 = System.currentTimeMillis();
        extraDTO.setDateTime(t1);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        PushDTO pushDTO = new PushDTO();
        pushDTO.setUserId(userIds);
        if (!StringUtils.isNullOrEmpty(appId)) {
            loginInfoDto.setAppId(appId);
        }
        pushDTO.setTitle(title);
        if (templateCode == null) {
            throw new RuntimeException("模板code参数有误！");
        }
        String templateDesc = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateDesc();
        for (Map.Entry<String, ?> content : templateContentMap.entrySet()) {
            String key = content.getKey();
            String val = content.getValue().toString();
            if (templateDesc.indexOf(key) > -1) {
                key = "\\{" + key + "\\}";
                templateDesc = templateDesc.replaceAll(key, val);
            }
        }
        pushDTO.setContent(templateDesc);
        pushDTO.setMode("notify");
        if (StringUtils.isNullOrEmpty(pushDTO.getTitle())) {
            String appNameQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.APP_NAME, loginInfoDto.getAppId());
            pushDTO.setTitle((StringUtils.isNullOrEmpty(appNameQ) ? appName : appNameQ));
        }
        if (StringUtils.isNullOrEmpty(pushDTO.getContent())) {
            pushDTO.setContent("模板错误！");
        }
        pushDTO.setExtra(extraDTO);
        pushByUserIdOrEmpNo(pushDTO);
    }


    @RequestMapping(value = "/pushBys", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "消息推送")
    public void pushBys(
            @RequestParam(value = "kind", required = false, defaultValue = "") Integer kind,
            @RequestParam(value = "businessId", required = false, defaultValue = "") Integer businessId,
            @RequestParam(value = "orderID", required = false, defaultValue = "") String orderID,
            @RequestParam(value = "recordVersion", required = false, defaultValue = "") String recordVersion,
            @RequestParam(value = "actionId", required = false, defaultValue = "") String actionId,
            @RequestParam(value = "clueId", required = false, defaultValue = "") String clueId,
            @RequestParam(value = "clueType", required = false, defaultValue = "") String clueType,
            @RequestParam(value = "customerBusinessId", required = false, defaultValue = "") String customerBusinessId,
            @RequestParam(value = "dataType", required = false, defaultValue = "") String dataType,
            @RequestParam(value = "userIds", required = true) Integer userIds,
            @RequestParam(value = "title", required = false, defaultValue = "") String title,
            @RequestParam(value = "templateCode", required = true, defaultValue = "") Integer templateCode,
            @RequestBody Map<String, Object> templateContentMap
    ) {
        ExtraDTO extraDTO = new ExtraDTO();
        extraDTO.setAppRole(templateCode);
        extraDTO.setBusinessId(businessId);
        extraDTO.setKind(kind);
        extraDTO.setOrderID(orderID);
        extraDTO.setRecordVersion(recordVersion);
        extraDTO.setDataType(dataType);
        extraDTO.setActionId(actionId);
        extraDTO.setClueId(clueId);
        extraDTO.setCustomerBusinessId(customerBusinessId);
        extraDTO.setClueType(clueType);   //区分类型
        extraDTO.setTemplateCode(templateCode);
        if (StringUtils.isNullOrEmpty(kind)) {
            extraDTO.setKind(0);
        }
        if (StringUtils.isNullOrEmpty(orderID)) {
            extraDTO.setOrderID("");
        }
        if (StringUtils.isNullOrEmpty(recordVersion)) {
            extraDTO.setRecordVersion("");
        }
        if (StringUtils.isNullOrEmpty(clueId)) {
            extraDTO.setClueId("");
        }
        if (StringUtils.isNullOrEmpty(actionId)) {
            extraDTO.setActionId("");
        }
        if (StringUtils.isNullOrEmpty(customerBusinessId)) {
            extraDTO.setCustomerBusinessId("");
        }

        if (StringUtils.isNullOrEmpty(clueType)) {
            extraDTO.setClueType("");
        }

        if (StringUtils.isNullOrEmpty(templateCode)) {
            extraDTO.setTemplateCode(70281003);
        }
        String appId = userMapper.selectById(userIds).getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new DALException("AppId不存在!");
        }
        String templateName = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateName();
        extraDTO.setTzType(templateName);
        extraDTO.setPushType(SysAuthCommonConstants.NOTICE_TZ);
        long t1 = System.currentTimeMillis();
        extraDTO.setDateTime(t1);

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        PushDTO pushDTO = new PushDTO();
        pushDTO.setUserId(userIds);

        if (!StringUtils.isNullOrEmpty(appId)) {
            loginInfoDto.setAppId(appId);
        }
        pushDTO.setTitle(title);
        if (templateCode == null) {
            throw new RuntimeException("模板code参数有误！");
        }
        String templateDesc = msgTemplateService.selectTempInfo(templateCode, appId).getTemplateDesc();
        for (Map.Entry<String, ?> content : templateContentMap.entrySet()) {
            String key = content.getKey();
            String val = content.getValue().toString();
            if (templateDesc.indexOf(key) > -1) {
                key = "\\{" + key + "\\}";
                templateDesc = templateDesc.replaceAll(key, val);
            }
        }
        pushDTO.setContent(templateDesc);
        pushDTO.setMode("notify");
        if (StringUtils.isNullOrEmpty(pushDTO.getTitle())) {
            String appNameQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.APP_NAME, loginInfoDto.getAppId());
            pushDTO.setTitle((StringUtils.isNullOrEmpty(appNameQ) ? appName : appNameQ));
        }
        if (StringUtils.isNullOrEmpty(pushDTO.getContent())) {
            pushDTO.setContent("模板错误！");
        }
        pushDTO.setExtra(extraDTO);
        pushByUserIdOrEmpNo(pushDTO);
    }


    /**
     * @description：短信验证码发送
     * @author ：quankk
     * @date ：Created in 2019/5/14 16:21
     * @modified By：
     */
    @RequestMapping(value = "/sendSms", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "短信验证码发送")
    public SendSmsResultDTO sendSms(@ApiParam(name = "smsType", value = "验证码类型，1：绑定手机号，2：登录，3：忘记密码，4：微信登录验证", required = true) @RequestParam(value = "smsType") Short smsType,
                                    @ApiParam(name = "phone", value = "手机号码", required = true) @RequestParam(value = "phone") String phone) throws Exception{
        return userLoginService.sendSms(smsType, phone);
    }

    /**
     * @description：手机号是否绑定
     * @author     ：quankk
     * @date       ：Created in 2019/5/17 15:33
     * @modified By：
     */
//    @RequestMapping(value = "/ifBinding", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "手机号是否绑定， 0： 未绑定 ，1： 已绑定")
//    private int ifBinding(@ApiParam(name = "phone", value = "手机号", required = true) @RequestParam(value = "phone") String phone){
//        return userLoginService.ifBinding(phone);
//    }

    /**
     * @description：绑定手机号码
     * @author ：quankk
     * @date ：Created in 2019/5/17 16:02
     * @modified By：
     */
    @RequestMapping(value = "/bindPhone", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "绑定手机号码")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public String bindPhone(@Valid @RequestBody BindPhoneDTO bindPhoneDTO) {
        return userLoginService.bindPhone(bindPhoneDTO);
    }

    /**
     * @author ：quankk
     * @date ：2019/5/20 18:30
     * @description：校验手机号验证码
     */
    @RequestMapping(value = "/ignore/verifyCheckCode", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "校验手机号验证码")
    public String verifyCheckCode(@Valid @RequestBody BindPhoneDTO bindPhoneDTO) {
        return userLoginService.verifyCheckCode(bindPhoneDTO);
    }

    /**
     * @author ：quankk
     * @date ：2019/5/21 17:19
     * @description：忘记密码修改密码
     */
    @ApiOperation(value = "忘记密码修改密码")
    @RequestMapping(value = "/ignore/forgetUpdatePassword", method = RequestMethod.POST, produces = "application/json")
    public String forgetUpdatePassword(@Valid @RequestBody PasswordDTO passwordDTO) throws Exception {
        return userLoginService.forgetUpdatePassword(passwordDTO);
    }

    /**
     * @author ：quankk
     * @date ：2019/5/22 11:46
     * @description：微信绑定，修改，解绑
     */
    @RequestMapping(value = "/bindWeChart", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "微信绑定，修改，解绑")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public String bindWeChart(@RequestBody BindPhoneDTO bindPhoneDTO) {
        return userLoginService.bindWeChart(bindPhoneDTO);
    }

    /**
     * @author ：quankk
     * @date ：2019/5/22 15:06
     * @description：个人信息
     */
    @RequestMapping(value = "/empInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "个人信息")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public EmpInfoDTO empInfo() throws Exception {
        logger.info("++++++++++++++++++++++++++++++进入control");
        return userLoginService.empInfo();
    }

    /**
     * @author ：quankk
     * @date ：2019/5/22 15:44
     * @description：修改保存个人信息
     */
    @RequestMapping(value = "/updateEmpInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "修改保存个人信息")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public String updateEmpInfo(@RequestBody EmpInfoDTO empInfoDTO) {
        return userLoginService.updateEmpInfo(empInfoDTO);
    }

    /**
     * 密码登陆
     *
     * @param loginDto 包含用户名密码
     * @return com.yonyou.ccss.userauth.entity.dto.UserInfoDto
     * @author houkaihua
     * @since 2018/11/6
     */
    @PostMapping("/byPassword")
    public UserInfoDto login(@RequestBody LoginDto loginDto) {
        logger.debug("登陆参数：{}", loginDto);
        return userService.viliateUserPass(loginDto);
    }

    /**
     * @author ：adu
     * @date ：2019/8/19 15:25
     * @description：根据查询条件返回对应的用户数据 PC迁移
     */
    @RequestMapping(value = "/userDetailData", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "据查询条件返回对应的用户数据 PC迁移")
    public Map<String, Object> initUserData() {
        return userLoginService.initUserData();
    }

    /**
     * 9984
     *
     * @author ：quankk
     * @date ：2019/7/8 16:18
     * @description：加载用户的菜单 PC迁移
     */
    @RequestMapping(value = "/getMenus", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "加载用户的菜单 PC迁移")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public List<MenuVueDto> getMenus() {
        return userLoginService.getMenus();
    }

    /**
     * 9984
     *
     * @author ：马邢健
     * @date ：2019/7/8 16:18
     * @description：加载用户的菜单 PC迁移
     */
    @RequestMapping(value = "/getFavoriteMenus", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "加载用户收藏菜单")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public List<MenuVueDto> getFavoriteMenus() {
        return userLoginService.getFavoriteMenus();
    }

    /**
     * @author ：quankk
     * @date ：2019/7/8 16:18
     * @description：加载用户的操作按钮功能 PC迁移
     */
    @RequestMapping(value = "/handles", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "加载用户的操作按钮功能 PC迁移")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public List<Map> handles() {
        return userLoginService.handles();
    }


    /**
     * 发送获得验证码
     *
     * @author ：李贺
     * @date ：2019/10/29
     */
    @PostMapping("/verificationCode")
    @ApiOperation(value = "发送获得验证码")
    public void verificationCode(@RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "appId", required = true) String appId, @RequestParam(value = "bindingPhone", required = false) Integer bindingPhone) {
        userLoginService.verificationCode(phone, appId, bindingPhone);
    }

    /**
     * 用户绑定手机号
     *
     * @author ：李贺
     * @date ：2019/10/29
     */
    @PostMapping("/bindingPhone")
    @ApiOperation(value = "用户绑定手机号")
    public void bindingPhone(@RequestBody BindingPhoneVO bindingPhoneVO) {
        userLoginService.bindingPhone(bindingPhoneVO);
    }

    /**
     * 获得当前车厂是否有微信登录和短信发送
     *
     * @author ：李贺
     * @date ：2019/12/5
     */
    @GetMapping("/getSmsWx")
    @ApiOperation(value = "获得当前车厂是否有微信登录和短信发送")
    public SmsWxVo getSmsWx(@RequestParam("appId") String appId) {
        return userLoginService.getSmsWx(appId);
    }

    /**
     * 获得头像
     *
     * @author ：李贺
     * @date ：2019/12/5
     */
    @GetMapping("/getHeadPortrait")
    @ApiOperation(value = "获得头像")
    public String getHeadPortrait() {
        return userLoginService.getHeadPortrait();
    }


    @Autowired
    EmployeeClientService employeeClientService;

    @RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "加载用户的菜单 PC迁移")
    public List<UserbyRoleVO> test() {
        return employeeClientService.getUserInfoByRolePosition("10061013", "3", "G00020201");
    }

    /**
     * 获取是否需要更新密码
     *
     * @author 李贺
     * @since 2019-12-12
     */
    @GetMapping("/needUpdate")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    public Integer needUpdate() {
        return systemParamService.needUpdate();
    }

    @Autowired
    LoginService loginService;
    @Autowired
    PushServices pushServices;

    @RequestMapping(value = "/test22", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "测试短信发送")
    public String test2(@RequestParam("code") String code) {
        SmsPushDTO smsPushDTO = new SmsPushDTO();
        smsPushDTO.setMobiles("17756132917");
        smsPushDTO.setTemplateId("470225");
        Map<String, String> params = new HashMap<>();
        params.put("1", code);
        params.put("2", "5");
        smsPushDTO.setParamMap(params);
        String f4Result = pushServices.sendSms(smsPushDTO);
        return f4Result;
    }


}
